import discord
import asyncio
import re

# 这里填写创建机器人时生成的token
discord_bot_token = "MTE5NjY2ODczMzE2NzUwOTU0NQ.G977V7.PmbXzCol2tU6vEN_dnibcAfHBs2HIlLOLTZV_I"

# 如果希望通过代理连接discord服务器，可以设置http proxy参数
client = discord.Client(proxy="http://127.0.0.1:7890")
#client = discord.Client()


@client.event
async def on_ready():
    print("Bot client logged-in as: %s" % client.user)
    # 展示 `Playing xxx` 状态
    custom_activity = discord.Game('discord.py')
    await client.change_presence(status=discord.Status.online, activity=custom_activity)


@client.event
async def on_member_join(member):
    # 发送结构化消息
    embed_str = discord.Embed(title="my test server",
                              description=f"Hi {member.name}, "
                                          f"welcome to the official {member.guild.name} Discord Server!",

                              color=0x00ff00)
    await member.create_dm()
    await member.dm_channel.send(embed=embed_str)
    # 发送普通文本消息
    # await member.dm_channel.send(
    #     f'Hi {member.name}, welcome to the official {member.guild.name} Discord Server!'
    # )


@client.event
async def on_message(message):
    # 排除bot自身的消息
    if message.author == client.user:
        return

    # ping/pong测试，然后删除测试消息
    if message.content == 'ping':
        tmp_msg = await message.channel.send('pong')
        await asyncio.sleep(3)
        await tmp_msg.delete()
        await message.delete()
    # 返回at机器人的消息
    elif client.user.mentioned_in(message):
        trim_mentioned_msg = re.sub("<@!?(\d+)>", "", message.content).strip()
        await message.channel.send(
            f"{message.author.mention} Message received: {trim_mentioned_msg}")
    else:
        print("Do nothing with message: %s" % message.content)


# 启动机器人
client.run(discord_bot_token)